import api from './api';
import type { RegisterRequest, LoginRequest, User, UpdateUserRequest, ChangePasswordRequest, ApiResponse } from '../types';

// 用户服务
const userService = {
  // 用户注册
  register: async (data: RegisterRequest): Promise<{ user: User; token: string }> => {
    const response = await api.post('/auth/register', data);
    return response;
  },

  // 用户登录
  login: async (data: LoginRequest): Promise<{ user: User; token: string }> => {
    const response = await api.post('/auth/login', data);
    // 存储token和用户信息到localStorage
    if (response.token) {
      localStorage.setItem('token', response.token);
      localStorage.setItem('userInfo', JSON.stringify(response.user));
    }
    return response;
  },

  // 用户登出
  logout: (): void => {
    localStorage.removeItem('token');
    localStorage.removeItem('userInfo');
    window.location.href = '/login';
  },

  // 获取当前登录用户信息
  getCurrentUser: (): User | null => {
    const userInfo = localStorage.getItem('userInfo');
    if (userInfo) {
      try {
        const user = JSON.parse(userInfo);
        // 将字符串日期转换为Date对象
        if (user.createdAt) user.createdAt = new Date(user.createdAt);
        if (user.updatedAt) user.updatedAt = new Date(user.updatedAt);
        if (user.lastLogin) user.lastLogin = new Date(user.lastLogin);
        return user;
      } catch (error) {
        console.error('解析用户信息失败:', error);
        return null;
      }
    }
    return null;
  },

  // 获取用户信息（通过ID）
  getUserInfo: async (userId?: string): Promise<ApiResponse<User>> => {
    try {
      const endpoint = userId ? `/users/${userId}` : '/users/me';
      const response = await api.get(endpoint);
      return {
        success: true,
        data: response
      };
    } catch (error) {
      console.error('获取用户信息失败:', error);
      return {
        success: false,
        error: error instanceof Error ? error.message : '获取用户信息失败'
      };
    }
  },

  // 更新用户资料
  updateProfile: async (data: UpdateUserRequest): Promise<ApiResponse<User>> => {
    try {
      const response = await api.put('/users/profile', data);
      // 更新localStorage中的用户信息
      const currentUser = userService.getCurrentUser();
      if (currentUser) {
        const updatedUser = { ...currentUser, ...response, updatedAt: new Date() };
        localStorage.setItem('userInfo', JSON.stringify(updatedUser));
      }
      return {
        success: true,
        data: response
      };
    } catch (error) {
      console.error('更新用户资料失败:', error);
      return {
        success: false,
        error: error instanceof Error ? error.message : '更新用户资料失败'
      };
    }
  },

  // 修改密码
  changePassword: async (passwordData: ChangePasswordRequest): Promise<ApiResponse<{ message: string }>> => {
    try {
      const response = await api.put('/users/password', passwordData);
      return {
        success: true,
        data: { message: response.message || '密码修改成功' }
      };
    } catch (error) {
      console.error('修改密码失败:', error);
      return {
        success: false,
        error: error instanceof Error ? error.message : '修改密码失败'
      };
    }
  },

  // 获取用户游戏历史
  getGameHistory: async (): Promise<ApiResponse<any[]>> => {
    try {
      const response = await api.get('/users/history');
      return {
        success: true,
        data: response
      };
    } catch (error) {
      console.error('获取游戏历史失败:', error);
      return {
        success: false,
        error: error instanceof Error ? error.message : '获取游戏历史失败'
      };
    }
  },

  // 上传头像
  uploadAvatar: async (file: File): Promise<ApiResponse<{ avatar: string }>> => {
    try {
      const formData = new FormData();
      formData.append('avatar', file);
      const response = await api.post('/users/avatar', formData, {
        headers: {
          'Content-Type': 'multipart/form-data'
        }
      });
      // 更新localStorage中的用户信息
      const currentUser = userService.getCurrentUser();
      if (currentUser) {
        currentUser.avatar = response.avatar;
        localStorage.setItem('userInfo', JSON.stringify(currentUser));
      }
      return {
        success: true,
        data: response
      };
    } catch (error) {
      console.error('上传头像失败:', error);
      return {
        success: false,
        error: error instanceof Error ? error.message : '上传头像失败'
      };
    }
  },

  // 获取用户的成就
  getUserAchievements: async (userId?: string): Promise<ApiResponse<any[]>> => {
    try {
      const endpoint = userId ? `/users/${userId}/achievements` : '/users/me/achievements';
      const response = await api.get(endpoint);
      return {
        success: true,
        data: response
      };
    } catch (error) {
      console.error('获取成就失败:', error);
      return {
        success: false,
        error: error instanceof Error ? error.message : '获取成就失败'
      };
    }
  },

  // 获取排行榜数据
  getLeaderboard: async (type: 'points' | 'wins' | 'winRate' = 'points'): Promise<ApiResponse<any[]>> => {
    try {
      const response = await api.get(`/leaderboard?type=${type}`);
      return {
        success: true,
        data: response
      };
    } catch (error) {
      console.error('获取排行榜失败:', error);
      return {
        success: false,
        error: error instanceof Error ? error.message : '获取排行榜失败'
      };
    }
  },

  // 检查用户是否已登录
  isLoggedIn: (): boolean => {
    return !!localStorage.getItem('token') && !!userService.getCurrentUser();
  },

  // 验证token是否有效
  validateToken: async (): Promise<boolean> => {
    try {
      const token = localStorage.getItem('token');
      if (!token) {
        return false;
      }
      
      const response = await api.get('/auth/validate');
      return response.valid === true;
    } catch (error) {
      console.error('验证token失败:', error);
      return false;
    }
  },

  // 重置密码（发送重置链接）
  forgotPassword: async (email: string): Promise<ApiResponse<{ message: string }>> => {
    try {
      const response = await api.post('/auth/forgot-password', { email });
      return {
        success: true,
        data: { message: response.message || '重置密码链接已发送到您的邮箱' }
      };
    } catch (error) {
      console.error('发送重置链接失败:', error);
      return {
        success: false,
        error: error instanceof Error ? error.message : '发送重置链接失败'
      };
    }
  },

  // 验证邮箱
  verifyEmail: async (token: string): Promise<ApiResponse<{ message: string }>> => {
    try {
      const response = await api.get(`/auth/verify-email?token=${token}`);
      return {
        success: true,
        data: { message: response.message || '邮箱验证成功' }
      };
    } catch (error) {
      console.error('验证邮箱失败:', error);
      return {
        success: false,
        error: error instanceof Error ? error.message : '验证邮箱失败'
      };
    }
  }
};

export default userService;